package com.syuchen.client.http;

import com.syuchen.protocol.http.Response;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 从流中获取报文，并解析为Response对象
 */
public class HttpDecoder {

    public static Response decode(InputStream inputStream) throws IOException {
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        Response response = new Response();

        parseFirstLine(response, responseReader);
        parseHeaders(response, responseReader);
        parseBody(response, responseReader);

        return response;
    }

    private static void parseFirstLine(Response response, BufferedReader responseReader) throws IOException {
        String firstLine = responseReader.readLine();
        String[] firstLineStrings = firstLine.split("\\s");
        response.setVersion(firstLineStrings[0]);
        response.setStatus_code(Integer.valueOf(firstLineStrings[1]));
        response.setStatus_description(firstLineStrings[2]);
    }

    private static void parseHeaders(Response response, BufferedReader responseReader) throws IOException {
        Map<String, String> headers = new HashMap<>();
        String headerString = responseReader.readLine();
        while (!headerString.equals("")) {
            String[] strs = headerString.split(":");
            headers.put(strs[0].trim(), strs[1].trim());
            headerString = responseReader.readLine();
        }
        response.setHeaders(headers);
    }

    private static void parseBody(Response response, BufferedReader requestReader) throws IOException {
        int contentLength = Integer.parseInt(response.getHeaders().getOrDefault("Content-Length", "0"));
        if (contentLength == 0) {
            return;
        }
        char[] body = new char[contentLength];
        int read = requestReader.read(body);
        response.setBody(new String(body));
    }
}
